<template>
    <div style="padding: 20px;">
        <div v-if="flag">
            <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="ruleFormRef" :size="formSize">
                <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="formInline.name" placeholder="请输入客户姓名" clearable />
                </el-form-item>
                <el-form-item label="客户手机" prop="phone">
                    <el-input v-model="formInline.phone" placeholder="请输入客户手机号码" clearable />
                </el-form-item>
                <el-form-item label="归属人" prop="owner">
                    <el-input v-model="formInline.owner" placeholder="请输入线索归属人" clearable />
                </el-form-item>
                <el-form-item label="线索渠道" prop="channelId">
                    <el-select v-model="formInline.channelId" placeholder="线索渠道" clearable>
                        <template v-for="(item, index) in channels" :key="index">
                            <el-option :label="item.channelName" :value="item.channelId" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="线索状态" prop="status">
                    <el-select v-model="formInline.status" placeholder="线索状态" clearable>
                        <el-option label="已分配" :value="1" />
                        <el-option label="跟进中" :value="2" />
                        <el-option label="回收" :value="3" />
                        <el-option label="伪线索" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="跟进时间" prop="timer">
                    <el-date-picker v-model="formInline.timer" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getLineList" :icon="Search">搜索</el-button>
                    <el-button :icon="Refresh" @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 增删改查 -->
        <div style="display: flex;justify-content: space-between;">
            <div class="btn-info">
                <el-button type="primary" :icon="Plus" plain @click="addInfo">新增</el-button>
                <el-button :disabled="edit" @click="editActiveInfo" type="success" :icon="Edit" plain>修改</el-button>
                <el-button :disabled="deleteBtn" type="danger" :icon="Delete" plain @click="deleteline">删除</el-button>
                <el-button type="warning" :icon="Upload" plain @click="handleExport">导出</el-button>
            </div>
            <div>
                <el-tooltip class="box-item" effect="dark" :content="flag ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button :icon="Search" circle @click="hiddenSearch" />
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="刷新" placement="top">
                    <el-button :icon="Refresh" circle @click="reFresh" />
                </el-tooltip>
            </div>
        </div>
        <!-- 表格 -->
        <div>
            <el-table ref="multipleTableRef" :data="tableData" style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column property="clueId" label="线索编号" width="100">
                </el-table-column>
                <el-table-column property="name" label="客户姓名" width="100" />
                <el-table-column property="phone" label="手机号" width="200" />
                <el-table-column property="channelName" label="渠道来源" width="100" />
                <el-table-column property="createTime" label="创建时间">
                    <template #default="scope">
                        <span>{{ formatDate(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column property="owner" label="线索归属" width="100" />
                <el-table-column property="status" label="线索状态" width="100">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status == 1">已分配</el-tag>
                        <el-tag v-else-if="scope.row.status == 2" type="success">跟进中</el-tag>
                        <el-tag v-else-if="scope.row.status == 3" type="danger">回收</el-tag>
                        <el-tag v-else-if="scope.row.status == 4" type="warning">伪线索</el-tag>
                        <span v-else></span>
                    </template>
                </el-table-column>
                <el-table-column property="nextTime" label="下次跟进时间">
                    <template #default="scope">
                        <span>{{ formatDate(scope.row.nextTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope" width="300">
                        <el-button text type="primary" :icon="View" @click="lookLine(scope.row)">查看</el-button>
                        <el-button v-if="scope.row.status !== '1'" text type="primary" :icon="TopRight"
                            @click="gj(scope.row)">跟进</el-button>
                        <el-button v-if="scope.row.status != '2'" text type="primary" :icon="Connection"
                            @click="fp(scope.row)">分配</el-button>
                        <el-button v-if="scope.row.status == '3'" text type="primary" :icon="Connection">回收</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="current">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                hide-on-single-page @current-change="handleCurrentChange" />
        </div>
        <!-- 模态框 -->
        <div>
            <el-dialog v-model="dialogFormVisible" :title="dialog ? '添加线索' : '修改线索'" width="800">
                <el-form :inline="true" ref="ruleForm" :model="form" class="demo-form-inline" label-width="100">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" clearable />
                    </el-form-item>
                    <el-form-item label="客户姓名" prop="name">
                        <el-input v-model="form.name" placeholder="请输入客户姓名" clearable />
                    </el-form-item>
                    <el-form-item label="线索渠道" prop="channelId">
                        <el-select v-model="form.channelId" @change="showInfo" placeholder="渠道来源" clearable>
                            <template v-for="(item, index) in channels" :key="index">
                                <el-option :label="item.channelName" :value="item.channelId" />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="活动信息" prop="activityId">
                        <el-select v-model="form.activityId" placeholder="活动信息" clearable>
                            <template v-for="(item, index) in infoactivity" :key="index">
                                <el-option :label="item.name" :value="item.activityId" />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="form.gender">
                            <el-radio :value="0">男</el-radio>
                            <el-radio :value="1">女</el-radio>
                            <el-radio :value="2">未知</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="客户年龄" prop="age">
                        <el-input-number v-model="form.age" @change="handleChange" max="100" min="1" />
                    </el-form-item>
                    <el-form-item label="微信号" prop="weixin">
                        <el-input v-model="form.weixin" placeholder="请输入微信号" clearable />
                    </el-form-item>
                    <el-form-item label="QQ号" prop="qq">
                        <el-input v-model="form.qq" placeholder="请输入QQ号" clearable />
                    </el-form-item>
                    <el-form-item>
                        <div class="dialog-footer">
                            <el-button v-if="dialog" type="primary" @click="NewinfoActive(ruleForm)">
                                确定
                            </el-button>
                            <el-button v-else type="primary" @click="editInfo(ruleForm)">
                                确定
                            </el-button>
                            <el-button @click="cancelInfo(ruleForm)">取消</el-button>
                        </div>
                    </el-form-item>
                </el-form>

            </el-dialog>
        </div>



        <!-- 分配模态框 -->
        <el-dialog v-model="dialogfp" title="分配线索" width="500">
            <el-form :model="xsxs">
                <el-form-item label="归属线索">
                    <el-tree-select v-model="value" :data="fpxs" check-strictly :render-after-expand="false"
                        style="width: 240px" />
                </el-form-item>
                <el-form-item label="分配给">
                    <el-select v-model="fpnr" placeholder="选择用户" style="width: 240px" @change="change">
                        <el-option v-for="item in user" :key="item.deptId" :label="item.nickName" :value="item.deptId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="ok">确定</el-button>
                    <el-button type="primary" @click="no">
                        取消
                    </el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script lang="ts" setup>
import { Delete, Edit, Search, Upload, Plus, Refresh, View, TopRight, Connection } from '@element-plus/icons-vue'
import { ref, reactive, toRaw, watch } from 'vue'
import { ElTable, ComponentSize, FormInstance, ElMessageBox, ElMessage } from 'element-plus'
import { lineList, deletelineList, channelsList, activityInfo, saveInfoActive, summaryInfo, editInfoActive, getfpxs, getfpuser, getassignment } from '../../../utils/api';
import { formatDate } from '../../../utils/index';
import { useRouter } from 'vue-router';
const { proxy } = getCurrentInstance();
const router = useRouter()
// 刷新
const loading = ref(false)
// 表单内容
const formInline = reactive({
    pageNum: 1,
    pageSize: 10,
    name: "",
    phone: "",
    owner: "",
    channelId: "",
    status: "",
    timer: "",
    dateRange: [],
    params: {
        beginTime: "",
        endTime: ""
    }

})
// 控制组件大小
const formSize = ref<ComponentSize>('default')
// 表单重置规则
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormInstance>()

// 刷新按钮
const reFresh = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        getLineList()
    }, 1000)
}
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    reFresh()
}
// 表格
interface User {
    clueId: string,
    name: string,
    phone: string,
    channelName: string,
    createTime: string,
    createBy: string,
    status: string,
    nextTime: string,
}
// 表格数据渲染
const tableData = ref<User[]>()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
// 选中显示的表格
const multipleSelection = ref<User[]>([])
// 表格选中事件
const edit = ref(true)
const deleteBtn = ref(true)
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(multipleSelection.value, '选中数据');
    if (multipleSelection.value.length !== 0) {
        deleteBtn.value = false
        if (multipleSelection.value.length == 1) {
            edit.value = false
        } else {
            edit.value = true
        }
    } else {
        edit.value = true
        deleteBtn.value = true
    }
}
// 删除选中数据
const deleteline = () => {
    let arr = []
    for (let index = 0; index < multipleSelection.value.length; index++) {
        const element = multipleSelection.value[index];
        console.log(element, "选中");
        arr.push(element.clueId)
    }
    ElMessageBox.confirm(
        '是否删除选中的文件夹?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deletelineList(arr).then((res) => {
                console.log(res);
                if (res.code == '200') {
                    reFresh()
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    edit.value = true
                    deleteBtn.value = true
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

// 操作
const handleEdit = (i, r) => {
    console.log(i, r);
}
// 查看
const lookLine = (r) => {
    console.log(r.clueId);
    router.push("/clue/details/index/" + r.clueId + "/view")
}
// 
const gj = (r) => {
    console.log(r.clueId);
    router.push("/clue/details/index/" + r.clueId + "/follow")
}
// 分页
const total = ref(0)
const currentPage = ref()
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    formInline.pageSize = val
    getLineList()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    formInline.pageNum = val
    getLineList()
}

// 表头隐藏
const flag = ref(true)
const hiddenSearch = () => {
    flag.value = !flag.value
}

// 模态框
const dialog = ref(true)
const dialogFormVisible = ref(false)
// const formLabelWidth = '300px'
let form = reactive({
    activityId: "",
    age: null,
    channelId: "",
    gender: "",
    name: "",
    phone: "",
    qq: "",
    weixin: ""
})

// 新增模态框
const addInfo = () => {
    form = reactive({
        activityId: "",
        age: null,
        channelId: "",
        gender: "",
        name: "",
        phone: "",
        qq: "",
        weixin: ""
    })
    dialogFormVisible.value = true
    dialog.value = true

}
// 保存模态框数据
const NewinfoActive = (formEl: FormInstance | undefined) => {
    dialogFormVisible.value = false
    console.log(form);
    saveInfoActive(form).then((res) => {
        console.log(res);
        if (res.code == '200') {
            formEl.resetFields()
            reFresh()
            ElMessage({
                type: 'success',
                message: '添加成功',
            })
        }
    })
}
// 取消模态框
const cancelInfo = (formEl: FormInstance | undefined) => {
    form = reactive({
        activityId: "",
        age: null,
        channelId: "",
        gender: "",
        name: "",
        phone: "",
        qq: "",
        weixin: ""
    })
    dialogFormVisible.value = false
    formEl.resetFields()
}
// 修改模态框
const editActiveInfo = async () => {

    dialog.value = false
    let element = multipleSelection.value[0]
    console.log(element.clueId);
    await summaryInfo(element.clueId).then((res) => {
        console.log(res);
        if (res.code == '200') {
            form = reactive(res.data)
            console.log(form, '-----------------')
            dialogFormVisible.value = true
        }
        console.log(form);
    })
}
const editInfo = (formEl: FormInstance | undefined) => {
    dialogFormVisible.value = false
    console.log(form);
    editInfoActive(form).then((res) => {
        console.log(res);
        if (res.code == '200') {
            formEl.resetFields()
            reFresh()
            ElMessage({
                type: 'success',
                message: '添加成功',
            })
        }
    })
}
// 年龄
const handleChange = (value: number) => {
    console.log(value)
}
// 获取线索列表
const getLineList = () => {
    if (formInline.timer.length == 0) {
        lineList(formInline).then((res) => {
            if (res.code == '200') {
                console.log(res, "线索");
                tableData.value = res.rows
                total.value = res.total
            }
        })
    } else {
        formInline.dateRange = formInline.timer
        formInline.params.beginTime = formInline.timer[0]
        formInline.params.endTime = formInline.timer[1]
        console.log(formInline);
        lineList(formInline).then((res) => {
            if (res.code == '200') {
                console.log(res, "线索");
                tableData.value = res.rows
                total.value = res.total
            }
        })
    }
}
// 渠道来源信息
const channels = ref()
getLineList()
const getchannelsList = () => {
    channelsList().then((res) => {
        if (res.code == '200') {
            channels.value = res.data
        }
    })
}
// 选择渠道显示活动信息
const infoactivity = ref()
const showInfo = (v) => {
    console.log(v, 111);
    activityInfo(v).then((res) => {
        console.log(res, '--------');
        infoactivity.value = res.data
    })
}

// 导出
function handleExport() {
    proxy.download("/tienchin/course/export", {
        ...ruleForm.value,
    }, `导出内容_${new Date().getTime()}.xlsx`);
};

const dialogfp = ref(false)

// 分配
const value = ref()
const fpnr = ref()
const xsxs = ref()
const user = ref()
watch(value, async () => {
    await getfpuser(value.value).then((r) => {
        console.log(r, 'tyuytrewertyu')
        // user.value = ''
        fpnr.value = ''
        user.value = r.data
    })
})
const userId = ref()
const fpxs = ref()
const fp = async (v: any) => {
    console.log('分配', v)
    userId.value = v.clueId
    await getfpxs().then((r) => {
        console.log(r)
        fpxs.value = renameIdToValue(r.data)
        dialogfp.value = true
        console.log(fpxs.value, '23456765432')
    })
}
// 分配用户
const change = () => {
    console.log(fpnr.value)
}

// 处理id值
function renameIdToValue(obj) {
    if (Array.isArray(obj)) {
        // 如果是数组，则递归处理每个元素
        return obj.map(item => renameIdToValue(item));
    } else if (typeof obj === 'object' && obj !== null) {
        // 如果是对象，则递归处理每个属性
        const newObj = {};
        for (const [key, value] of Object.entries(obj)) {
            // 如果遇到 'id' 键，则改为 'value' 键
            if (key === 'id') {
                newObj['value'] = renameIdToValue(value);
            } else {
                newObj[key] = renameIdToValue(value);
            }
        }
        return newObj;
    }
    // 对于其他类型，直接返回
    return obj;
}
const ok = () => {
    // dialogfp.value = false
    console.log(userId.value, Array.from(toRaw(user.value)), value.value)
    flt(Array.from(toRaw(user.value)), value.value, userId.value, fpnr.value)

}
// 过滤符合分配用户的具体数据
function flt(data, value, userid, fpnr) {
    for (let i = 0; i < data.length; i++) {
        if (data[i].deptId == fpnr) {
            console.log(data[i], value, userid, '获取关键数据')
            // 请求分配内容接口
            getassignment({
                assignId: userid,
                departmentId: value,
                deptId: fpnr,
                nickName: data[i].nickName,
                type: 0,
                userId: data[i].userId,
                userName: data[i].userName
            }).then((r) => {
                console.log(r, '请求成功')
                if (r.code == 200) {
                    dialogfp.value = false
                    ElMessage({
                        message: r.msg,
                        type: 'success',
                    })
                    getLineList()
                }
            }).catch((r) => {
                ElMessage({
                    message: r.msg,
                    type: 'error',
                })
            })
        }
    }
}
const no = () => {
    dialogfp.value = false
}



getchannelsList()
</script>

<style lang="scss" scoped>
.h-btn {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 20px;
}

.h-btn2 {
    width: 640px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 20px;
}

.btn-info {
    margin-bottom: 20px;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.current {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>